<?php
    class Admincp_Model_Page extends Zend_Db_Table_Abstract
    {
        protected $_db;
        
        public function __construct()
        {
            $this->_db = Zend_Registry::get('db');
        }
        
        public function listPage($locale)
        {
            $sql = $this->_db->select()
                            ->from('page AS p')
                            ->join('page_language AS pl', 'p.id = pl.page_id', array('title'))
                            ->join('language AS l', 'pl.language_id = l.id', null)
                            ->where('l.locale = ?', $locale)
                            ->order('p.id DESC');
            return $sql;
        }
        
        public function getPageById($id)
        {
            $sql = $this->_db->select()
                            ->from('page_language AS pl', array('title', 'description'))
                            ->join('language AS l', 'pl.language_id = l.id', array('locale'))
                            ->where('pl.page_id = ?', $id);
            $result = $this->_db->fetchAll($sql);
            return $result;
        }
        
        public function checkPage($title, $id = null)
        {
            $sql = $this->_db->select()
                            ->from('page_language')
                            ->where('title = ?', $title);
            if($id != null) {
                $sql = $sql->where('page_id <> ?', $id);
            }
            $result = $this->_db->fetchAll($sql);
            return count($result);
        }
        
        public function addPage($data)
        {
            $this->_db->insert('page',$data);
            return $this->_db->lastInsertId();
        }
        
        public function addPageLanguage($data)
        {
            $this->_db->insert('page_language',$data);
        }
        
        public function updatePage($data, $id)
        {
            $where = $this->getAdapter()->quoteInto('id = ?', $id);
            $this->_db->update('page', $data, $where);
        }
        
        public function updatePageLanguage($data,$id)
        {
            $where = 'page_id = '.$id.' AND language_id = '.$data['language_id'];
            $this->_db->update('page_language', $data, $where);
        }
        
        public function deletePage($id)
        {
            $where = $this->getAdapter()->quoteInto('id = ?', $id);
            $this->_db->delete('page', $where);
            $where = $this->getAdapter()->quoteInto('page_id = ?', $id);
            $this->_db->delete('page_language', $where);
        }
        
        public function deleteMultiPage($listId)
        {
            foreach($listId as $id) {
                $this->deletePage($id);
            }
        }
    }
